package com.example.spring_async.controller;

import com.example.spring_async.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * @Author: banban
 * @Desctription: TODO
 * @Date: Created in 2024/1/20 22:26
 * @Version: 1.0
 */
@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("sendMails")
    public String sendMails() {
        String[] emails = new String[]{"1234@qq.com","5678@qq.com,"};
        for (int i = 0; i < emails.length; i++) {
            asyncService.sendMail(emails[i], "test");
        }
        return "success";
    }

    @GetMapping("blockSendMails")
    public String blockSendMails() {
        CompletableFuture<String>[] future = new CompletableFuture[2];
        String[] emails = new String[]{"1234@qq.com","5678@qq.com,"};
        for (int i = 0; i < emails.length; i++) {
            future[i] = asyncService.blockSendMail(emails[i], "test");
        }
        //阻塞等待所有CompletableFuture
        CompletableFuture.allOf(future);

        StringBuffer out = new StringBuffer();
        for (int i = 0; i < future.length; i++) {
            try {
                out.append(future[i].get() + "\n");
            }catch (Exception e){

            }
        }
        return out.toString();
    }

}
